var util = require("../../../utils/util.js"),
    {
        api
    } = require("../../../utils/api.js"),
    app = getApp();
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        multiArray: [],
        pageIndex: 1,
        pageScroll: !0,
        storeName: "",
        showEmpty: !1,
        city: '',
        storeList: [],
        cityIndex: [0, 0],
        cityOrignList: [],
        area: '',
        type: 1,
        multiActive: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.qqmapsdk = new QQMapWX({
            key: app.globalData.mapKey
        });
        this.setData({
            type: options.type,
            goods_id: options.id
        });
        this.getUserSetting();

    },
    getUserSetting() {
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.cancel) {
                                wx.showToast({
                                    title: '拒绝授权',
                                    icon: 'none',
                                    duration: 1000
                                })
                                that.getAreaList()
                            } else if (res.confirm) {
                                wx.openSetting({
                                    success: function (dataAu) {
                                        if (dataAu.authSetting["scope.userLocation"] == true) {
                                            wx.showToast({
                                                title: '授权成功',
                                                icon: 'success',
                                                duration: 1000
                                            })
                                            that.getLocationAddress();
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                                icon: 'none',
                                                duration: 1000
                                            })
                                            that.getAreaList();
                                        }
                                    },
                                    fail: function () {
                                        that.getAreaList();
                                    }
                                })
                            }
                        }
                    })
                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    that.getLocationAddress();
                } else {
                    that.getLocationAddress();
                }
            },
            fail: function () {
                that.getAreaList();
            }
        })
    },
    getLocationAddress() {
        let positionUpdateTime = wx.getStorageSync('positionUpdateTime');
        if (positionUpdateTime && positionUpdateTime < new Date().getTime()) {
            this.getAreaList();
            return false;
        }
        let that = this;
        wx.getLocation({
            type: 'wgs84',
            success(res) {
                console.log('wgs84', res)
                const {
                    latitude,
                    longitude
                } = res;
                if (latitude && longitude) {
                    wx.setStorageSync('latitude', latitude);
                    wx.setStorageSync('longitude', longitude);
                    wx.setStorageSync('positionUpdateTime', (new Date().getTime() + 14400000));
                    that.getAreaList();
                    // that.qqmapsdk.reverseGeocoder({
                    //     location: {
                    //         latitude,
                    //         longitude
                    //     },
                    //     success: function (result) {
                    //         console.log('result', result)
                    //         if (result.status === 0 && result.result && result.result.address_component) {
                    //             let area=result.result.address_component.district;
                    //             that.getAreaList(area);
                    //         } else {
                    //             that.getAreaList();
                    //         }
                    //     },
                    //     fail: function (err) {
                    //         console.log('err', err)
                    //         that.getAreaList()
                    //     }
                    // })
                } else {
                    that.getAreaList()
                }
            },
            fail: function () {
                that.getAreaList()
            }
        })
    },
    async getStoreGoodsList() {
        let {
            data
        } = await api.getStoreGoodsList({
            goods_id: this.data.goods_id,
            latitude: wx.getStorageSync('latitude'),
            longitude: wx.getStorageSync('longitude'),
        });
        this.setData({
            showEmpty: false,
            storeList: data && Array.isArray(data.store_list) ? data.store_list : [],
            pageScroll: false
        })
    },
    async getAreaList(area = null) {
        if (this.data.type == 2 || this.data.type == 3) {
            this.getStoreGoodsList();
            return;
        }
        let {
            data
        } = await api.getAreaList();
        let cityOrignList = Array.isArray(data.area_list) ? data.area_list : [],
            multiArray = [],
            isOf = false;
        cityOrignList.forEach(item => {
            let child = item.child && Array.isArray(item.child) ? item.child : [];
            child.forEach(val => {
                if (util.regularConfig.isString(val)) {
                    multiArray.push(val)
                }
                if (area && val === area) isOf = true;
            })
        })
        console.log('multiArray', multiArray);
        // let cityList = [],
        //     areaList = ['全部'],
        //     multiArray = [];
        // if (cityOrignList.length > 0) {
        //     cityList = cityOrignList.map(o => o.name);
        //     if (Array.isArray(cityOrignList[0].child) && cityOrignList[0].child.length > 0) {
        //         areaList = [...areaList, ...cityOrignList[0].child];
        //     }
        //     multiArray = [cityList, areaList];
        // }
        this.setData({
            // cityOrignList,
            // city: cityList.length > 0 ? cityList[0] : '',
            area: isOf ? area : (multiArray.length > 0 ? multiArray[0] : ''),
            multiArray: multiArray,
            // cityList
        })
        this.searchStore();
    },
    bindMultiPickerColumnChange(e) {
        let sIndex = e.detail.value,
            column = e.detail.column,
            cityOrignList = this.data.cityOrignList;
        if (column == 0) {
            let areaList = ['全部']
            if (cityOrignList[sIndex].child && Array.isArray(cityOrignList[sIndex].child) && cityOrignList[sIndex].child.length > 0) {
                areaList = [...areaList, ...cityOrignList[sIndex].child];
            }
            this.setData({
                multiArray: [this.data.cityList, areaList],
                cityIndex: [sIndex, 0]
            })
        } else if (column == 1) {
            this.data.cityIndex[1] = sIndex;
            this.setData({
                cityIndex: this.data.cityIndex
            })
        }
    },
    toMapNav(t) {
        var e = this.data.storeList[t.currentTarget.dataset.index];
        console.log('e', e);
        wx.openLocation({
            latitude: parseFloat(e.lat),
            longitude: parseFloat(e.lng),
            scale: 18,
            name: e.name,
            address: e.address
        });
    },
    goDetail(t) {
        const {id,index}=t.currentTarget.dataset;
        const detail=this.data.storeList[index];
        if (this.data.type == 3) {
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2];
            if (prevPage) {
                prevPage.setStoreDetail(detail);
                // 返回上一个页面
                wx.navigateBack({
                    delta: 1
                });
            }
            return;
        }
        wx.navigateTo({
            url: '/pages/shopping/storeDetail/storeDetail?id=' + id,
        })
    },
    cityChange(t) {
        this.setData({
            pageNum: 1,
            storeList: [],
            city: this.data.multiArray[this.data.cityIndex[0]],
            pageScroll: !0,
            cityIndex: t.detail.value
        })
        this.searchStore();
    },
    cityChanges(e) {
        this.setData({
            pageNum: 1,
            area: e.currentTarget.dataset.key,
            pageScroll: !0
        })
        this.searchStore();
    },
    onSearch(t) {
        this.setData({
            pageIndex: 1,
            storeList: [],
            storeName: t.detail,
            pageScroll: !0
        })
        this.searchStore();
    },
    makePhoneCall: function (t) {
        wx.makePhoneCall({
            phoneNumber: t.currentTarget.dataset.tel
        }).catch(function () {});
    },
    shopInfo: function (t) {
        let id = t.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/pages/mine/appointment/appointment?store_id=" + id
        });
    },
    async searchStore() {
        let {
            pageIndex,
            storeName,
            multiArray,
            cityIndex
        } = this.data;
        var formData = {
            page: pageIndex,
            pageSize: 10,
            // keyword: storeName,
            latitude: wx.getStorageSync('latitude'),
            longitude: wx.getStorageSync('longitude'),
            // city: multiArray[0][cityIndex[0]],
            // city: '上海市',
            // area: multiArray[1][cityIndex[1]] == '全部' ? '' : multiArray[1][cityIndex[1]]
            area: this.data.area
        };
        let {
            data: {
                list,
                total
            }
        } = await api.getStoreList(formData);
        let listArr = Array.isArray(list) ? list : [];
        this.setData({
            showEmpty: total == 0 ? true : false,
            storeList: pageIndex == 1 ? listArr : [...this.data.storeList, ...listArr],
            pageScroll: listArr.length < 10 ? false : true
        })
    },
    onShow: function () {},
    onReachBottom: function () {
        this.data.pageScroll && (this.setData({
            pageIndex: this.data.pageIndex + 1
        }), this.searchStore());
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        return util.shareEvent(e)
      }
})